package org.sauceggplant;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * RSA加解密
 *
 * @author jacob
 * @version 0.1
 */
public class RSAUtil {

    public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
        return doFinal(publicKey, Cipher.ENCRYPT_MODE, data);
    }

    public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
        return doFinal(privateKey, Cipher.DECRYPT_MODE, data);
    }

    private static byte[] doFinal(Key key, int mode, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance(PemUtil.ALGORITHM);
        cipher.init(mode, key);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = cipher.doFinal(data);
        baos.write(buffer, 0, buffer.length);
        byte[] result = baos.toByteArray();
        baos.close();
        return result;
    }
}
